import navigateTo from '@/utils/navigator';

export const useSearch = defineStore(
  'search',
  () => {
    let currentTitle = ref('');
    let history = ref<string[]>([]);

    // 关键字搜索历史记录排序
    function search(content: string) {
      if (content) {
        if (history.value.includes(content))
          history.value = history.value.sort((a) => (a === content ? -1 : 1));
        else history.value.unshift(content);
        history.value.length > 10 && history.value.pop();
      }
      navigateTo(`/pages/search/index?content=${content}`);
    }
    // 清除历史记录
    function clearHistory() {
      history.value = [];
    }
    // 设置输入框显示值
    function setCurrentTitle(content: string) {
      currentTitle.value = content;
    }

    return ({
      history,
      currentTitle,
      search,
      clearHistory,
      setCurrentTitle,
    });
  },
  {
    persist: true,
  }
);

